package com.li.qiqi.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.li.qiqi.config.CustomCellWriteHandler;
import com.li.qiqi.domain.QIct;
import com.li.qiqi.domain.Record;
import com.li.qiqi.service.QIctService;
import com.li.qiqi.service.RecordService;
import com.li.qiqi.vo.RecordVo;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/qiqi")
@CrossOrigin(allowCredentials = "true", maxAge = 3600)
public class MainController {
    @Resource
    private RecordService recordService;
    @Resource
    private QIctService qIctService;

    @PostMapping("insert")
    public void insert(@RequestBody Record record) {
        record.setTeaName("唐唐");
        record.setIsHomework("√");
        record.setStatus("√");
        if (record.getQType() != null && !record.getQType().equals("")) {
            record.setQType(qIctService.selectByPrimaryKey(record.getQType()).getQValue());
        }
        record.setStartTime(strDeal(record.getStartTime()));
        record.setEndTime(strDeal(record.getEndTime()));
        recordService.insert(record);
    }

    @GetMapping("list")
    public List<RecordVo> list() {
        return recordService.selectAll().stream().map(r -> {
            RecordVo recordVo = new RecordVo();
            recordVo.setIsHomework(r.getIsHomework());
            recordVo.setStatus(r.getStatus());
            recordVo.setQType(r.getQType());
            recordVo.setStartTime(r.getStartTime());
            recordVo.setEndTime(r.getEndTime());
            recordVo.setId(r.getId());
            if (r.getStartTime().startsWith("0")) {
                recordVo.setStartTime(r.getStartTime().substring(1));
            }
            if (r.getEndTime().startsWith("0")) {
                recordVo.setEndTime(r.getEndTime().substring(1));
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM月dd号");
            String format = dateFormat.format(r.getQDate());
            String month = format.split("-")[1];
            if (month.startsWith("0")) {
                recordVo.setQDate(month.substring(1));
            } else {
                recordVo.setQDate(month);
            }
            return recordVo;
        }).collect(Collectors.toList());
    }

    @GetMapping("del")
    public Boolean delById(@Param("id") Integer id) {
        int delete = recordService.deleteByPrimaryKey(id);
        return delete == 1;
    }

    @GetMapping("month")
    public List<Record> month(@Param("month") String month) {
        return recordService.selectByDate(month);

    }

    @GetMapping("addDict")
    public int addDict(@Param("course") String course) {
        return qIctService.addDict(QIct.builder()
                .qValue(course)
                .id(IdUtil.getSnowflake().nextIdStr())
                .build());
    }

    @GetMapping("month/dict")
    public List<QIct> month() {
        return recordService.selectMonthList().stream().map(m -> {
            return QIct.builder()
                    .qValue(m)
                    .build();
        }).collect(Collectors.toList());

    }

    @GetMapping("dict")
    public List<QIct> dict() {
        return qIctService.selectAll();
    }

    @GetMapping("export")
    public void download(HttpServletResponse response, String recordMonth) throws IOException {
        Optional.ofNullable(recordMonth).orElseThrow(RuntimeException::new);
        String monthName = recordMonth.split("-")[1] + "月";
        List<Record> recordList = recordService.selectByDate(recordMonth).stream()
                .map(rec -> {
                    String format = DateUtil.format(rec.getQDate(), "MM月dd号");
                    if (format.startsWith("0")){
                        format = format.substring(1);
                    }
                    rec.setExcelDate(format);
                    rec.setExcelType(rec.getQType());
                    if (rec.getStartTime().startsWith("0")) {
                        rec.setStartTime(rec.getStartTime().substring(1));
                    }
                    if (rec.getEndTime().startsWith("0")) {
                        rec.setEndTime(rec.getEndTime().substring(1));
                    }
                    return rec;
                }).collect(Collectors.toList());
        String fileName = "北苑教师考勤.唐唐" + monthName + ".xlsx";
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));

        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short)11);
        headWriteFont.setFontName("宋体");

        headWriteCellStyle.setWriteFont(headWriteFont);
        headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        headWriteCellStyle.setBorderTop(BorderStyle.THIN);
        headWriteCellStyle.setBorderRight(BorderStyle.THIN);
        headWriteCellStyle.setBorderBottom(BorderStyle.THIN);

        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);

        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        //需要合并的列
        int[] mergeColumeIndex = {0};
        //需要从第一行开始，列头第一行
        int mergeRowIndex = 1;
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), Record.class)
                .registerWriteHandler(new CustomCellWriteHandler(mergeRowIndex,mergeColumeIndex))
                .registerWriteHandler(horizontalCellStyleStrategy)
                .build();
        excelWriter.write(recordList, EasyExcel.writerSheet("sheet1").build());
        excelWriter.finish();
    }

    public String strDeal(String time) {
        String ret = time.replace(":", "点");
        String res = ret.replace("00", "");
//        if (res.startsWith("0")) {
//            return res.substring(1);
//        }
        return res;
    }
}
